package struts.parser;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import struts.action.AbstractAction;
import struts.config.ActionConfig;
import struts.config.StrutsConfig;


public class StrutsXmlParser {
	public static void parseXml(String strutsConfigName)  {
		try {
			SAXBuilder builder=new SAXBuilder();
			Document doc=builder.build(StrutsXmlParser.class.getResourceAsStream(strutsConfigName));
			Element root=doc.getRootElement();
			Element formBean=root.getChild("formBean");
			Element actiomMapper=root.getChild("actionMapper");
			@SuppressWarnings("unchecked")
			List<Element> actions=actiomMapper.getChildren("action");
			for (Element action : actions) {
				ActionConfig actionConfig=new ActionConfig();
				String name=action.getAttributeValue("name");
				actionConfig.setActionName(name);
				String className=action.getAttributeValue("class");
				actionConfig.setClassName(className);
				String refForm=action.getAttributeValue("refForm");
				Element form=formBean.getChild("refForm");
				String formClassName=form.getAttributeValue("class");
				actionConfig.setRefForm(formClassName);
				String path=action.getAttributeValue("path");
				actionConfig.setPath(path);
				@SuppressWarnings("unchecked")
				List<Element> results=action.getChildren("result");
				Map<String,String> resutMap=new HashMap<>();
				for (Element result : results) {
					resutMap.put(result.getAttributeValue("name"), result.getText());
				}
				Class clazz=Class.forName(actionConfig.getClassName());
				actionConfig.setAction((AbstractAction)clazz.newInstance());
				actionConfig.setResutMap(resutMap);
				StrutsConfig.addActionConfig(actionConfig.getPath(), actionConfig);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("StrutsXml配置文件解析异常");
		}
	}
}
 